package cn.edu.zjicm.wordsnet_d.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.activity.base.LoginWeixinBaseActivity;
import cn.edu.zjicm.wordsnet_d.activity.base.WordBaseActivity;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.synchronize.HeadImageInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.PayInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;
import cn.edu.zjicm.wordsnet_d.util.DataValidator;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.view.EmailAutoCompleteTextView;
import cn.edu.zjicm.wordsnet_d.wxapi.WXEntryActivity;

import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

public class LoginActivity extends LoginWeixinBaseActivity implements OnClickListener, OnFocusChangeListener {

	public static void startActivity(Context context, boolean isAfterLogout) {
		Intent i = new Intent(context, LoginActivity.class);
		i.putExtra("isAfterLogout", isAfterLogout);
		context.startActivity(i);
	}

	public static void startActivity(Context context, boolean isAfterLogout, String lastUserID) {
		Intent i = new Intent(context, LoginActivity.class);
		i.putExtra("isAfterLogout", isAfterLogout);
		i.putExtra("lastUserID", lastUserID);
		context.startActivity(i);
	}

	private boolean isAfterLogout = false;
	private String lastUserID = "";
	public static LoginActivity mLoginActivity;

	private TextView toRegister;
	private TextView forgetPwd;
	private EmailAutoCompleteTextView loginID;
	private EditText password;
	private Button login;
	private ImageView email_clear, pwd_clear;
	private RelativeLayout loginWithWechat;

	private InputMethodManager imm;

	private Handler loginHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(LoginActivity.this, null, "正在登录...");
				break;
			case UserInterface.MSG_SUCCESS:
				// Toast.makeText(LoginActivity.this, "登录成功",
				// Toast.LENGTH_SHORT).show();
				toSync();
				toGetPunch();
				// ExpInterface.getInstance(LoginActivity.this).getExp();
				// //在登录接口已实现下传经验值，此处不用再获取经验值
				HeadImageInterface.getInstance(LoginActivity.this).downloadHeadImage();
				PayInterface.getInstance(LoginActivity.this).getUserWealth(); // 获取用户财富值
				PayInterface.getInstance(LoginActivity.this).getUserBought(); // 获取用户购买商品
				MobclickAgentData.login(LoginActivity.this, "登录成功");
				break;
			// case UserInterface.MSG_NOT_REGISTERED:
			// Toast.makeText(LoginActivity.this, "该邮箱尚未注册,不存在",
			// Toast.LENGTH_SHORT).show();
			// MobclickAgentData.login(LoginActivity.this, "登录失败，该邮箱尚未注册,不存在");
			// break;
			case UserInterface.MSG_INCORRECT_PASSWORD:
				Toast.makeText(LoginActivity.this, "邮箱或密码错误", Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，邮箱或密码错误");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(LoginActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(LoginActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，连接服务器失败");
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				Toast.makeText(LoginActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，服务器错误");
				break;
			default:
				break;
			}
		};
	};

	Handler syncHandler = new Handler() {
		ProgressDialog dialog2 = null;

		public void handleMessage(android.os.Message msg) {
			if (msg.what != UserInterface.MSG_START)
				if (dialog2 != null) {
					dialog2.dismiss();
					dialog2 = null;
				}

			switch (msg.what) {
			case UserInterface.MSG_START:
				dialog2 = ProgressDialog.show(LoginActivity.this, null, "正在同步用户数据...");
				break;
			case UserInterface.MSG_SUCCESS:
				Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录成功,同步成功");
				AppPreference.setFirstGuidePage(mLoginActivity, false);
				if (RegisterActivity.nextOperation == RegisterActivity.TO_MAIN || RegisterActivity.nextOperation == RegisterActivity.TO_PUNCH_OUT) {
					// if(hasLoginByWeixin == false)
					// PersonalAccountActivity.startActivity(LoginActivity.this,
					// PersonalAccountActivity.TYPE_REGISTER);
					// else
					if (AppPreference.hasStudyingBook(mLoginActivity))
						MainActivity.startActivity(LoginActivity.this);
					else
						SelectBookActivity.mStartActivity(LoginActivity.this, StaticData.MODE_INIT);

				} else if (RegisterActivity.nextOperation == RegisterActivity.TO_LEADER_BOARD) {
					LeaderboardActivity.startActivity(mLoginActivity);
				}
				if (RegisterActivity.mContext != null) {
					RegisterActivity.mContext.toFinish();
				}

				if (GuideActivityFull.mInstance != null) {
					GuideActivityFull.mInstance.toFinish();
				}

				toFinish();
				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(LoginActivity.this, "同步失败", Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，同步失败");
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(LoginActivity.this, UserInterface.MSG_BAD_NETWORK_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，同步失败，未检测到网络连接");
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(LoginActivity.this, UserInterface.MSG_WEB_SITE_ACCESS_FAILURE_STRING, Toast.LENGTH_SHORT).show();
				MobclickAgentData.login(LoginActivity.this, "登录失败，同步失败，连接服务器失败");
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mLoginActivity = LoginActivity.this;

		isAfterLogout = getIntent().getBooleanExtra("isAfterLogout", false);
		setTitleBarStyle(TITLE_BAR_STYLE_BACK_BUTTON);
		setTitleText("登录");
		if (isAfterLogout) {
			hideTitleBarBackButton();
		}

		lastUserID = getIntent().getStringExtra("lastUserID");

		setContentView(R.layout.activity_login);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		loginID = (EmailAutoCompleteTextView) findViewById(R.id.login_email);

		loginID.setText(lastUserID);
		email_clear = (ImageView) findViewById(R.id.login_email_clear);
		if (lastUserID != null) {
			loginID.requestFocus();
			loginID.setSelection(lastUserID.length());
			email_clear.setVisibility(View.VISIBLE);
		}
		loginID.setOnFocusChangeListener(this);

		password = (EditText) findViewById(R.id.login_pwd);
		password.setOnFocusChangeListener(this);
		password.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					if (login.isEnabled()) {
						checkAndLogin();
					}
					return true;
				}
				return false;
			}
		});

		login = (Button) findViewById(R.id.login_btn);

		email_clear.setOnClickListener(this);

		pwd_clear = (ImageView) findViewById(R.id.login_pwd_clear);
		pwd_clear.setOnClickListener(this);

		toRegister = (TextView) findViewById(R.id.login_toRegister);
		toRegister.setOnClickListener(this);

		forgetPwd = (TextView) findViewById(R.id.login_forgetPwd);
		forgetPwd.setOnClickListener(this);

		login.setOnClickListener(this);
		loginID.addTextChangedListener(textWatcher);
		password.addTextChangedListener(textWatcher);

		loginWithWechat = (RelativeLayout) findViewById(R.id.login_button_wechat);
		loginWithWechat.setOnClickListener(this);

		setBackButton(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toFinish();
			}
		});

		if (isAfterLogout && loginID.getText().length() > 0) {
			password.requestFocus();
		}

	}

	protected void toLogin() {
		loginHandler.sendMessage(loginHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(LoginActivity.this).login(loginID.getText().toString(), password.getText().toString(), loginHandler);
	}

	protected void toSync() {
		syncHandler.sendMessage(syncHandler.obtainMessage(UserInterface.MSG_START));
		UserInterface.getInstance(LoginActivity.this).sync(syncHandler);
	}

	void checkLoginInfo() {
		boolean flag = true;
		if (loginID.hasFocus()) {
			if (DataValidator.EditIsNull(loginID.getText().toString())) {
				flag = false;
				email_clear.setVisibility(View.GONE);
			} else {
				email_clear.setVisibility(View.VISIBLE);
			}
			if (DataValidator.EditIsNull(password.getText().toString())) {
				flag = false;
			}
		}

		if (password.hasFocus()) {
			if (DataValidator.EditIsNull(password.getText().toString())) {
				flag = false;
				pwd_clear.setVisibility(View.GONE);
			} else {
				pwd_clear.setVisibility(View.VISIBLE);
			}
			if (DataValidator.EditIsNull(loginID.getText().toString())) {
				flag = false;
			}
		}

		if (flag) {
			login.setEnabled(true);
		} else {
			login.setEnabled(false);
		}
	}

	TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			checkLoginInfo();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_email_clear:
			loginID.setText("");
			email_clear.setVisibility(View.GONE);
			break;

		case R.id.login_pwd_clear:
			password.setText("");
			pwd_clear.setVisibility(View.GONE);
			break;
		case R.id.login_btn:
			// Log.d("Tag",
			// "登录后selectedId为:"+AppPreference.getSelectedBookId(LoginActivity.this));
			checkAndLogin();
			break;
		case R.id.login_button_wechat:
			loginWithWeChat();
			// toLoginWeixin("oao06uCt5ptFImwIpMxdSg2EqJT11", "a", "a郑珺bc");
			break;
		case R.id.login_toRegister:
			if (RegisterActivity.mContext != null) {
				toFinish();
			} else {
				Intent in = new Intent(mLoginActivity, RegisterActivity.class);
				in.putExtra("email", loginID.getText().toString());
				startActivity(in);
			}
			break;
		case R.id.login_forgetPwd:
			Intent in = new Intent(mLoginActivity, ForgetPwdActivity.class);
			startActivity(in);
			break;
		}
	}

	private void checkAndLogin() {
		if (DataValidator.EditIsNull(loginID.getText().toString()) || DataValidator.EditIsNull(password.getText().toString())) {
			Toast.makeText(LoginActivity.this, "请将邮箱和密码填写完整", Toast.LENGTH_SHORT).show();
		} else if (!DataValidator.EmailIsValidate(loginID.getText().toString())) {
			Toast.makeText(LoginActivity.this, "请输入正确的电子邮箱", Toast.LENGTH_SHORT).show();
		} else {
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			toLogin();
		}
	}

	IWXAPI apiWeChat;

	private void loginWithWeChat() {
		apiWeChat = WXAPIFactory.createWXAPI(this, StaticData.APP_ID_WECHAT);
		if (apiWeChat.isWXAppInstalled()) {
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "ZhiMi_English";
			apiWeChat.sendReq(req);
			WXEntryActivity.context = this;
		} else {
			Toast.makeText(LoginActivity.this, "安装微信客户端后才能登录哦", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		switch (v.getId()) {
		case R.id.login_email:
			if (v.hasFocus() && !DataValidator.EditIsNull(loginID.getText().toString())) {
				email_clear.setVisibility(View.VISIBLE);
			} else {
				email_clear.setVisibility(View.GONE);
			}
			break;

		case R.id.login_pwd:
			if (v.hasFocus() && !DataValidator.EditIsNull(password.getText().toString())) {
				pwd_clear.setVisibility(View.VISIBLE);
			} else {
				pwd_clear.setVisibility(View.GONE);
			}
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean consumed = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			toFinish();
		}
		return consumed;
	}

	public void toFinish() {
		finish();
		mLoginActivity = null;
	}

}
